import { defineStore } from 'pinia'
import { ref, } from 'vue'


export const UseMenuStore = defineStore('UseMenuStore', () => {


    const isCollapse = ref(false)

    const selectMenu = ref([])
    const routerList = ref([])
        // 当前页面路由路径
    const RouterPath = ref('')
        // 当前高亮侧边栏
    const MenuActive = ref()

    const collapseMenu = () => {
        isCollapse.value = !isCollapse.value
    }

    // 添加tab栏
    const addMenu = (payload) => {
        // 遍历selectMenu这个数组，判断它的每一项中的path属性有没有和点击传递进来的item.path的值有没有冲突
        if (selectMenu.value.findIndex(item => item.path === payload.path) === -1) {
            selectMenu.value.push(payload)
        }
    }

    // 关闭高亮tab栏
    const closeMenu = (payload) => {
        const index = selectMenu.value.findIndex(item => item.name === payload.name)
        selectMenu.value.splice(index, 1)
    }

    // 获取用户路由信息
    const dynamicMenu = (payload) => {
        // console.log(payload);
        // 引入所有文件路径, 两个 * 号代表文件夹
        const modules =
            import.meta.glob('../../views/**/**/*.vue')
            // console.log(modules);

        function routerSet(router) {
            // console.log(router);

            router.forEach(route => {
                if (!route.children) {
                    // 判断没有子菜单，拼接路由数据
                    const url = `../../views${route.meta.path}/index.vue`
                        // console.log(url);
                        // console.log(modules[url]);
                        // 拿到modules里面属性并修改值
                    route.component = modules[url]
                } else {
                    // 有子菜单，拼接路由数据,递归
                    routerSet(route.children)
                }
            });
        }
        routerSet(payload)
            // 拿到完整的路由数据
        routerList.value = payload

    }

    return { isCollapse, selectMenu, collapseMenu, addMenu, closeMenu, dynamicMenu, routerList, RouterPath, MenuActive }
}, {
    persist: true
})